<style lang="scss" scoped>
    @import url('./audio.scss');
</style>
<template>
  <div class="audio">
      <div >
         <div class="audio-content" style='background-image: url("http://p1.music.126.net/jWdcbq8MxwEm9-rbdwBGZQ==/6040716883333198.jpg")'>
        <back></back>  
        <div class="audio-content-bg">
          <div class="music-title">
            长相思
            <div class="musicer">——&nbsp;唐嫣&nbsp;——</div>
          </div>
          <div id="wrap" class="swiper-container">
            <ul class="swiper-wrapper">
              <li class="swiper-slide audioe-content-bg">
                <img :class="audioStop ? 'play-bg stop' : 'play-bg' " src="http://p1.music.126.net/jWdcbq8MxwEm9-rbdwBGZQ==/6040716883333198.jpg" alt="">
              </li>
              <li class="swiper-slide lyric-content">
                <div class="lyric-bg">
                  <ul :style="'transform:'+translateY">
                    <li v-for="(item,index) in lyric" :key="index" :class="lyric[index+1] ?  audioObj.currentTime >= item.time && lyric[index+1].time > audioObj.currentTime? 'ative' : '' : audioObj.currentTime >= item.time ?'ative':''">
                      {{item.text}}
                    </li>
                  </ul>
                </div>
              </li>
            </ul>
          </div>
          <div class="play-control">
            <audio ref="audioObj" @timeupdate="timeUpdate()" :src="plays.musicAddress" autoplay ></audio>
            <div class="progress-control clearfix">
              <div class="currentTime">
                {{currentTime}}
              </div>
              <div class="progress" @click="dragProgress($event)" ref="progress">
                <div class="play-progress" :style="{width: progress + '%' }" ></div>
                <div class="play-progress-bar" draggable="true" @touchstart="touchStart($event)" @touchmove="touchMove($event)" @touchend="touchEnd($event)"></div>
              </div>
              <div class="duration">
                {{duration}}
              </div>
            </div>
            <div class="button-control clearfix">
              <div class="pre-control">
                <i class="iconfont icon-xiayishou"></i>
              </div>
              <div class="play-pause-control" v-if="!pauseStatus" @click="playMethed()">
                <i class="iconfont icon-bofang"></i>
              </div>
              <div class="play-pause-control"  v-if="pauseStatus" @click="pauseMethed()">
                <i class="iconfont icon-plus-pause"></i>
              </div>
              <div class="next-control">
                <i class="iconfont icon-next-9"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      </div>
  </div>
</template>

<script type="es6">
import store from './../store/index' ;
import back from './../components/back' ;
import { mapState } from 'vuex' ;
import anime from 'animejs'

import Swiper from 'swiper' ;
export default {
  data(){
      return {
        data:'这里是音乐播放' ,
        audioObj : ''  ,
        pauseStatus :true ,
        duration: '00:00',
        currentTime:'00:00',
        progress:'0' ,
        audioStop:false ,
        lyric :[] ,
        isEnd:false  ,
        first :true ,
        translateY:10.5,
        isShowing:false
      }
  },
  props:{
    resourceId:{
        type:String,
        default:''
    }
  },
  computed:mapState({
      plays : state => state.music.playLists || {} ,
  }),
  components:{
    back
  },
  mounted(){
    this.isShowing = true ;
    this.initSwiper()
    this.getMusic() ;
    this.audioObj =this.$refs.audioObj  || '' ;

    this.animeObj = anime({
        targets:'.audio',
        rotate: '1turn'
    })
  },
  beforeDestory(){
    // this.isShowing = false ;
    // this.animeObj.Update = () => {
    //   console.log()
    // }
    console.log('销毁组件')
  },
  methods:{
    initSwiper:function(){
        var mySwiper = new Swiper('#wrap', {
            // autoplay: 5000,//可选选项，自动滑动
        })
    },
    getMusic:function(){
        this.$store.dispatch(('getMusic'),{id:this.resourceId}).then(() => {
          this.lyric = this.lyricStringToObject(this.plays.lyric) ;
        });
    },
    playMethed:function(){
      this.audioObj.currentTime = this.getSecond(this.currentTime) ;
      this.pauseStatus = true ;
      this.audioStop = false ;
      if(this.isEnd){
        this.audioObj.load();
        this.isEnd = false  ;
      }else{
        this.audioObj.play();
      }
    },
    pauseMethed:function() {
      this.audioObj.pause() ;
      this.pauseStatus = false ;
      this.audioStop = true ;
    },
    progressMethed:function(el){
      
    },
    dragProgress:function(event){
      event.preventDefault() ;
      let currentX = event.offsetX ; 
      let progressX = event.target.clientWidth ;
      let progressNum  = (parseFloat(currentX) / parseFloat(progressX)) * 100
      this.progress =  progressNum >= 96.1 ?  96.1 : progressNum ;
      this.currentTime = this.getTime((this.progress / 100 ) * parseFloat(this.audioObj.duration)) ;
      this.audioObj.currentTime = this.getSecond(this.currentTime)
    },
    getTime:function(timer){
      let minute = Math.floor(timer/60) < 10 ? '0'+Math.floor(timer/60) : Math.floor(timer/60) ;
      let second = Math.floor(timer%60) < 10 ? '0' + Math.floor(timer%60) : Math.floor(timer%60);
      let timeText = (minute || '00')+':'+ (second || '00') ;
      return timeText ;
    },
    getSecond:function(timer){
      let sp = timer.split(':') ;
      return parseFloat(sp[0]*60) + parseFloat(sp[1]) ;
    },
    timeUpdate:function(){
      this.currentTime = this.getTime(this.audioObj.currentTime) ;
      let progressNum = (parseFloat(this.audioObj.currentTime) / parseFloat(this.audioObj.duration))*100  ;
      this.progress = progressNum >= 96.1 ?  96.1 : progressNum ;
      this.lyMove();
      if(this.audioObj.ended){
        this.pauseStatus = false ;
        this.isEnd = true ;
      }
      if(this.audioObj.readyState && this.first){
        this.duration = this.getTime(this.audioObj.duration) ;
        this.first = false ;
      }
    },
    lyricStringToObject:function(text) {
        let _this = this ;
        let array = [];
        text.split(/\n/g).forEach(text => {
            let obj = {};
            const sp = text.split(/]/g),
                lyText = sp[1];
            const lytime = sp[0].split('[')[1];
            if (lytime && lyText) {
                obj["time"] = _this.getTimeByStr(lytime);
                obj["text"] = lyText;
                array.push(obj);
            }
        });
        array.push({
            time:array[array.length-1].time+20,
            text:"完"
        });
        return array;
    },
    getTimeByStr:function( str ){
        let timeArray = str.split(":");
        return (timeArray[0]*60)+(timeArray[1]*1);
    },
    lyMove:function(){
        let currentTime = this.audioObj.currentTime ;
        let activeIndex = 1 ;
        this.lyric.forEach(function(item,index) {
          if(this.lyric[index+1] && currentTime >=item.time && currentTime<this.lyric[index+1].time){
            activeIndex = index+1 ;
          }else if(!this.lyric[index+1] && currentTime >= item.time){
            activeIndex = this.lyric.length
          }
        }, this);
        const runIndex = activeIndex<= 1 ? 1:activeIndex;
        this.translateY = 'translateY('+(parseFloat(4)- (runIndex == 1 ? 0 : parseFloat(runIndex*1.8)))+'rem)' ;
    },
    touchStart:function(event){
        this.progress = this.computeX(event) ;
    },
    touchMove:function(event){
        this.progress = this.computeX(event) ;
    },
    touchEnd:function(event){
      let progressNum = parseFloat(this.computeX(event)) * 100 ;
      this.progress =  progressNum >= 96.1 ?  96.1 : progressNum ;
      this.currentTime = this.getTime((this.progress / 100 ) * parseFloat(this.audioObj.duration)) ;
      console.log(parseFloat(this.computeX(event)) * 100)
      // this.audioObj.currentTime = this.getSecond(this.currentTime)
    },
    computeX:function(event){
      let currentNodepageX = event.targetTouches[0] ? event.targetTouches[0].pageX : 0;
      let progressWidth = this.$refs.progress.clientWidth ;
      let bodyWidth = document.body.clientWidth ; 
      let X = currentNodepageX - ((bodyWidth - progressWidth) / 2 ) ;
      let widthX = X / progressWidth ;
      let returnData = widthX <= 0 ? widthX : widthX >= 1 ? 1 : widthX ; 
      console.log(returnData)
      return returnData ;
    }
  },
  
}
</script>


